/*
 * @Descripttion:
 * @version:
 * @Author: 杨颖
 * @Date: 2022-03-09 13:37:47
 * @LastEditors: 杨颖
 * @LastEditTime: 2022-05-06 15:41:50
 */
let Socket = '';
let setIntervalWesocketPush = null;

/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = (url = process.env.VUE_APP_SOK || 'ws://123.207.31.14:8385') => {
  console.log(url, 'webSocket链接');
  Socket && Socket.close();
  if (!Socket) {
    console.log('建立websocket连接');
    Socket = new WebSocket(url);
    Socket.onopen = onopenWS;
    Socket.onmessage = onmessageWS;
    Socket.onerror = onerrorWS;
    Socket.onclose = oncloseWS1;
  } else {
    console.log('websocket已连接');
  }
};
export const close = () => {
  Socket.close();
  Socket = '';
};

/**打开WS之后发送心跳 */
const onopenWS = () => {
  sendPing();
};

/**连接失败重连 */
export const onerrorWS = () => {
  console.log('重连中');
  getData();
  Socket.close();
  clearInterval(setIntervalWesocketPush);
  // if (Socket.readyState !== 3) {
  Socket = null;
  createSocket();

  // }
};
const oncloseWS1 = () => {
  console.log('断开');
  clearInterval(setIntervalWesocketPush);

  // }
};

const getData = () => {
  var evt2 = document.createEvent('HTMLEvents');
  evt2.initEvent('getData', false, true);
  // let event= new Event('getData')
  evt2.detail = {};
  window.dispatchEvent(evt2);
};
/**WS数据接收统一处理 */
const onmessageWS = (e) => {
  var evt = document.createEvent('HTMLEvents');
  evt.initEvent('onmessageWS', false, true);
  // let event2= new Event('onmessageWS')
  evt.detail = { data: e.data };
  window.dispatchEvent(evt);
  // window.dispatchEvent(new CustomEvent('onmessageWS', {

  // }))
};

/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} message 需要发送的数据
 */
const connecting = (message) => {
  setTimeout(() => {
    if (Socket.readyState === 0) {
      connecting(message);
    } else {
      Socket.send(JSON.stringify(message));
    }
  }, 1000);
};

/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
export const sendWSPush = (message) => {
  if (Socket !== null && Socket.readyState === 3) {
    Socket.close();
    createSocket();
  } else if (Socket.readyState === 1) {
    Socket.send(JSON.stringify(message));
  } else if (Socket.readyState === 0) {
    connecting(message);
  }
};

/**断开重连 */
const oncloseWS = () => {
  clearInterval(setIntervalWesocketPush);
  console.log('websocket已断开....正在尝试重连');
  if (Socket.readyState !== 2) {
    Socket = null;
    createSocket();
  }
};
/**发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = (time = 15000, ping = 'webPing') => {
  clearInterval(setIntervalWesocketPush);
  Socket.send(ping);
  setIntervalWesocketPush = setInterval(() => {
    Socket.send(ping);
  }, time);
};
